--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local error_code = require("error_code")
local reason = require "reason"
local constant = require "constant"

local table_insert = table.insert


---------------------------------------------------------
-- class
---------------------------------------------------------
local MessageHandler = class("MessageHandler")

function MessageHandler:ctor(message_dispatch)
	self.message_dispatch = message_dispatch
	self.node_message = nil
	self.desk = nil
    self.ntf_bet_list = {} --需要推送的下注消息

	self:register()
end

--注册本服务里的消息
function MessageHandler:register()

	self.message_dispatch:registerSelf('REQ_BET',handler(self,self.betReq))
	
end

--初始化
function MessageHandler:start()
	self.room_config = global.room_config
	self.user_manager = global.user_manager
	self.desk = global.desk
    self.banker_manager = global.banker_manager

 	self.table_id = self.room_config:getTableId()
 	self.table_type = self.room_config:getTableType()
 	self.table_gid = self.room_config:getTableGid()
 	self.game_type = self.room_config:getGameType()



end

--定时推送下注消息
function MessageHandler:ntfBetMessage()
    for uid, info_list in pairs(self.ntf_bet_list) do
        if next(info_list) then 
            print("_222___ntfBetMessage______info___", uid, (info_list))
            self.desk:sendToOther("erbagang.NTF_BET", uid, info_list)
        end
        self.ntf_bet_list[uid] = nil
    end
end
---------------------------------------------------------
-- CMD
---------------------------------------------------------

--下注
--所有下注额度不能超过庄的持有量
function MessageHandler:betReq(uid, fd, msg)

    local user = self.user_manager:getUser(uid)
    if not user or not user:isFD(fd) then --玩家不在这个桌子里
        errlog(uid,'_____betReq但玩家不在这个桌子里______invalid status',user:getFD(), fd)
        return true
    end
	
	local state = self.desk:getState()
	if state~="bet" then 
		print("_____桌子不在下注状态不可以下注")        
		return true
	end
    if self.banker_manager:isBanker(user) then
        dbglog(uid,"_____betReq庄家不能下注_____", user:isRobot())
        return true
    end
    local all_bet_chip = self.desk:getAllBetChip()
    local banker = self.banker_manager:getBanker()
    local bet_chip = msg.bet_chip
    local pool_id = msg.pool_id
    local bet_type = msg.bet_type or 1 --下注方式 1正常，2续押
    -- local is_robot = user:isRobot()
    -- if not is_robot then 
    --     dbglog('_____betReq玩家下注______',uid, (msg))
    -- end
    if pool_id < 1 or pool_id > 3 then 
        deglog("______下注位置不对___", uid, pool_id)
        return true
    end
    if all_bet_chip + bet_chip > banker:getCoins() then 
        print("_______all_bet_chip______", all_bet_chip, bet_chip, banker:getCoins())
        --下注总额超过庄家上限
        self.desk:sendToUser(uid, "erbagang.RSP_BET", {result=error_code.EBG_BET_1})
        return true
    end

	--小于最小限制不给下注	    
    local min_bet = self.room_config:getMinBet()
    local start_coins = user:getInitCoins()
    -- dbglog("__bet________", bet_chip, user:getCoins(), start_coins, min_bet)
    if bet_chip > user:getCoins() then
        --下注额不足
        self.desk:sendToUser(uid, "erbagang.RSP_BET", {result=error_code.GOLD_IS_NOT_ENOUGH})
        return true
    end
    if start_coins <= min_bet then
        local res = self.room_config:getErrResult(error_code.EBG_BET_MIN_COINS_LIMIT, min_bet)
        self.desk:sendToUser(uid, "erbagang.RSP_BET", res)
        return true
    end    
    --下注位置检查
    local can_bet_list = user:getCanBetList()
    local can_bet = false
    for k, v in pairs(can_bet_list) do 
        if bet_chip == v then 
            can_bet = true
            break
        end
    end 
    if not can_bet and bet_type~=2 then 
        --下注额不在列表上
        -- self.desk:sendToUser(uid, "erbagang.RSP_BET", {result=error_code.BET_FAIL, description="下注额不在列表上"})
        return true
    end  
    --限红检查
    local room_data = self.room_config:getRoomData()
    --个人限红
    local person_limit = room_data.person_limit
    if bet_chip < person_limit[1] then 
        --下注小过个人限红
        self.desk:sendToUser(uid, "erbagang.RSP_BET", {result=error_code.BJL_BET_1})
        return false, 2
    end    
    if self.desk:getUserBet(uid) + bet_chip > person_limit[2] then 
        --下注超过个人限红
        self.desk:sendToUser(uid,  "erbagang.RSP_BET", {result=error_code.BJL_BET_2})        
        return false, 3
    end
    local player_limit = {
        room_data.person_tian_limit,
        room_data.person_di_limit,
        room_data.person_ren_limit,            
    }
    if self.desk:getPoolUserBet(pool_id, uid) + bet_chip > player_limit[pool_id] then 
        --下注超过个人区域限红
        self.desk:sendToUser(uid,  "erbagang.RSP_BET",{result=error_code.BJL_BET_3})        
        return false, 4
    end
    --池总限红
    local pool_limit = {        
        room_data.area_tian_limit,        
        room_data.area_di_limit,
        room_data.area_ren_limit,        
    }   
    if pool_limit[pool_id]>0 and self.desk:getPoolAllBet(pool_id) + bet_chip > pool_limit[pool_id] then 
        --下注超过池总限红
        self.desk:sendToUser(uid,  "erbagang.RSP_BET",{result=error_code.BJL_BET_4})
        return false, 5
    end

    --去扣钱
    local ret = self.desk:reduceChip(uid, bet_chip, reason.BET_COIN)    
    if not ret then
        self.desk:sendToUser(uid,'erbagang.RSP_BET',{result = error_code.GOLD_IS_NOT_ENOUGH})
        return false, 8
    end

    -- 异步完后，必须是可押注状态
	local state = self.desk:getState()
	if state~="bet" then 
        errlog(uid,'游戏状态不对failed to check status',bet_chip,state)
        --如果此时不可押注，则返回钱
        local ret = self.desk:addChip(uid, bet_chip, reason.BET_COIN_BACK)    
        if not ret then
            --加钱失败
            errlog(uid,'返回钱失败', bet_chip)
        end        
        self.desk:sendToUser(uid, 'erbagang.RSP_BET',{result = error_code.BET_FAIL})
        return false, 9
    end

    self.desk:setUserBet(user, bet_chip, pool_id)
    user:setBeted(true) --已下注
    user:addCurBet(bet_chip)
    user:addTotalBet(bet_chip)
    user:setNoBetCount(0)
    --通知玩家本人金币发生变化
    self.desk:ntMoneyChanged(uid, {coins = user:getCoins()}, constant.MONEY_CHANGED_REASON.erbagang_BET)
    --失去金币
    self.desk:sendLoseCoin(uid, bet_chip)
    local bet_info = {
        uid = uid,
        pool_id = pool_id,
        total_coins = self.desk:getPoolAllBet(pool_id), --池总分 
        player_total = self.desk:getPoolUserBet(pool_id, uid), --玩家总下注
        cur_bet = bet_chip, 
        cur_coins = user:getCoins(),
    } 			
    local res = {
    	result = 0, --0表示下注成功
    	bet_info = bet_info, --
    }
    self.desk:sendToUser(uid, "erbagang.RSP_BET", res)

    -- if not self.ntf_bet_list[uid] then 
    --     self.ntf_bet_list[uid] = {bet_list={}}
    -- end
    --定时推送下注消息   
    -- table_insert(self.ntf_bet_list[uid].bet_list, bet_info)
    -- dbglog("____1111_____下注成功___", (bet_info))

    self.desk:sendToOther("erbagang.NTF_BET", uid, {bet_list={bet_info}})

    return true
end



return MessageHandler